//
//  YWSelectInspectLineEquipmentTableViewController.m
//  maintain
//
//  Created by Kyo on 16/10/11.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectInspectLineEquipmentTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "MJRefresh.h"
#import "YWLoginTool.h"
#import "UIScrollView+EmptyDataSet.h"

#import "DOPDropDownMenu.h"

#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWBuildingManager.h"
#import "YWEquipment.h"
#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"

@interface YWSelectInspectLineEquipmentTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,DOPDropDownMenuDataSource,DOPDropDownMenuDelegate>{
    YWApartment *currentApartment;
    YWFloor *currentFloor;
    YWLocation *currentLocation;
    YWEquipmentSubSystemType *currentSubSystem;
    YWEquipmentType *currentEquipmentType;
    
    NSInteger page;
}
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) NSMutableArray *menuDataArray;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *selectEquipmentArray;

@end

@implementation YWSelectInspectLineEquipmentTableViewController

//- (instancetype)init{
//    return [super  initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"finish", nil) style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
    
    [self setupDataSource];
    // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
    [self.menu selectDefalutIndexPath];
    
    [self setupOwnEquipmentArray];
    [self initTableView];
}

- (void)setupDataSource{
    page = 1;
    NSInteger equipmentTypeId = 0;
    if (_equipmentTypeId>0) {
        equipmentTypeId = _equipmentTypeId;
        currentEquipmentType = [[YWEquipmentType alloc] init];
        currentEquipmentType.equipmentTypeId = equipmentTypeId;
        NSString *equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:equipmentTypeId];
        currentEquipmentType.equipmentTypeName = equipmentTypeName;
    }
    
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentsWithBuildingId:self.buildingId ApartmentId:0 floorId:0 locationId:0 eqipmentSubSystemType:0 equipmentTypeId:equipmentTypeId page:page];
    [self.dataSource addObjectsFromArray:equipments];
}

- (NSMutableArray *)menuDataArray{
    if (!_menuDataArray) {
        _menuDataArray = [NSMutableArray array];
        
        NSMutableArray *apartmentMut = [NSMutableArray array];
        YWApartment *apartment = [[YWApartment alloc] init];
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartment.apartmentName = apartmentShowName.length? apartmentShowName:NSLocalizedString(@"apartment", nil);
        [apartmentMut addObject:apartment];
        
        NSArray *apartmentArray = [[YWBuildingManager shareManager] apartmentWithbuildingId:self.buildingId];
        [apartmentMut addObjectsFromArray:apartmentArray];
        
        NSMutableArray *floorMut = [NSMutableArray array];
        YWFloor *floor = [[YWFloor alloc] init];
        NSString *floorShowName = [YWLoginTool floorShowName];
        floor.floorName = floorShowName.length? floorShowName:NSLocalizedString(@"floor", nil);
        [floorMut addObject:floor];
        
        NSMutableArray *locationMut = [NSMutableArray array];
        YWLocation *location = [[YWLocation alloc] init];
        NSString *locationShowName = [YWLoginTool locationShowName];
        location.locationName = locationShowName.length? locationShowName:NSLocalizedString(@"location", nil);
        [locationMut addObject:location];
        
        NSMutableArray *typeMut = [NSMutableArray array];
        if (_equipmentTypeId>0) {
            [typeMut addObject:currentEquipmentType];
        }else{
            YWEquipmentSubSystemType *subSystem = [[YWEquipmentSubSystemType alloc] init];
            subSystem.subSystemTypeName = NSLocalizedString(@"type", nil);
            [typeMut addObject:subSystem];
            
            NSArray *subSystemType = [[YWEquipmentManager shareManager] allEquipmentSubSystemType];
            [typeMut addObjectsFromArray:subSystemType];
        }
        
        [_menuDataArray addObject:apartmentMut];
        [_menuDataArray addObject:floorMut];
        [_menuDataArray addObject:locationMut];
        [_menuDataArray addObject:typeMut];
        
    }
    return _menuDataArray;
}
- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (void)initTableView{
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 52.0f;
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    [self.tableView setEditing:YES];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
}

- (void)refreshFootor{
    page++;
    [self.dataSource removeAllObjects];
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentsWithBuildingId:self.buildingId ApartmentId:currentApartment.apartmentId floorId:currentFloor.floorId locationId:currentLocation.locationId eqipmentSubSystemType:currentSubSystem.subSystemTypeId equipmentTypeId:currentEquipmentType.equipmentTypeId page:page];
    [self.dataSource addObjectsFromArray:equipments];
    
    [self setupOwnEquipmentArray];
    
    [self.tableView.mj_footer endRefreshing];
    [self.tableView reloadData];
}

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return self.menuDataArray.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_menuDataArray[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        return apartment.apartmentName;
    }else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        return floor.floorName;
    }else if (indexPath.column == 2){
        YWLocation *location = _menuDataArray[indexPath.column][indexPath.row];
        return location.locationName;
    }else if (indexPath.column ==3){
        if (_equipmentTypeId>0) {
            YWEquipmentType *equipmentType = _menuDataArray[indexPath.column][indexPath.row];
            return equipmentType.equipmentTypeName;
        }else{
            YWEquipmentSubSystemType* subSystem = _menuDataArray[indexPath.column][indexPath.row];
            return subSystem.subSystemTypeName;
        }
    }
    return nil;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
{
    if (column==3 && _equipmentTypeId==0) {
        YWEquipmentSubSystemType* subSystem = _menuDataArray[column][row];
        return subSystem.equipmentTypeArray.count;
    }
    return 0;
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column==3 && _equipmentTypeId==0) {
        YWEquipmentSubSystemType* subSystem = _menuDataArray[indexPath.column][indexPath.row];
        YWEquipmentType *equipmentType = subSystem.equipmentTypeArray[indexPath.item];
        return equipmentType.equipmentTypeName;
    }
    return nil;
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    BOOL needSelect = NO;
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        if (currentApartment.apartmentId!=apartment.apartmentId) {
            needSelect = YES;
            currentApartment = apartment;
            currentFloor = nil;
            currentLocation = nil;
            
            NSMutableArray *floorMut = [NSMutableArray array];
            YWFloor *floor = [[YWFloor alloc] init];
            NSString *floorShowName = [YWLoginTool floorShowName];
            floor.floorName = floorShowName.length? floorShowName:NSLocalizedString(@"floor", nil);
            [floorMut addObject:floor];
            
            NSArray *floorArray = [[YWBuildingManager shareManager] floorWithApartmentId:currentApartment.apartmentId];
            [floorMut addObjectsFromArray:floorArray];
            
            [_menuDataArray replaceObjectAtIndex:1 withObject:floorMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:1 row:0];
            [_menu selectIndexPath:reloadIndexPath];
            reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
        
    } else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        if (currentFloor.floorId != floor.floorId) {
            needSelect = YES;
            currentFloor = floor;
            currentLocation = nil;
            
            NSMutableArray *locationMut = [NSMutableArray array];
            YWLocation *location = [[YWLocation alloc] init];
            NSString *locationShowName = [YWLoginTool locationShowName];
            location.locationName = locationShowName.length? locationShowName:NSLocalizedString(@"location", nil);
            [locationMut addObject:location];
            
            NSArray *locationArray = [[YWBuildingManager shareManager] locationWithFloorId:currentFloor.floorId];
            [locationMut addObjectsFromArray:locationArray];
            
            [_menuDataArray replaceObjectAtIndex:2 withObject:locationMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
    }else if (indexPath.column == 2){
        YWLocation *location = _menuDataArray[indexPath.column][indexPath.row];
        if (currentLocation.locationId != location.locationId) {
            needSelect = YES;
            currentLocation = location;
        }
    }else if (indexPath.column == 3){
        needSelect = YES;
        if (_equipmentTypeId>0) {
            YWEquipmentType *equipmentType = _menuDataArray[indexPath.column][indexPath.row];
            currentEquipmentType = equipmentType?:nil;
        }else{
            YWEquipmentSubSystemType* subSystem = _menuDataArray[indexPath.column][indexPath.row];
            if (indexPath.item >= 0) {
                if (subSystem.equipmentTypeArray.count>0) {
                    YWEquipmentType *equipmentType = subSystem.equipmentTypeArray[indexPath.item];
                    currentEquipmentType = equipmentType?:nil;
                }else{
                    currentEquipmentType = nil;
                }
            }else{
                currentSubSystem = subSystem;
                currentEquipmentType = nil;
            }
        }
    }
    if (needSelect) {
        page = 1;
        [self rightNowSelect];
    }
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"YWSelectInspectionEquipmentCellReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
        cell.textLabel.font = kContentFont;
        cell.detailTextLabel.font = KSmallContentFont;
        cell.detailTextLabel.textColor = [UIColor customTextGrayColor];
    }
    YWEquipment *equipment = _dataSource[indexPath.row];
    cell.textLabel.text = equipment.equipmentName?:@"";
    cell.detailTextLabel.text = [[YWBuildingManager shareManager] equipmentLocationNobuilding:equipment]?:[NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"location", nil),NSLocalizedString(@"none", nil)];
    return cell;
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    return _menu;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    YWEquipment *equipment = _dataSource[indexPath.row];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equipment.equipmentId];
    NSArray *array = [self.selectEquipmentArray filteredArrayUsingPredicate:searchPredicate];
    if (array.count>0) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YWEquipment *equipment = _dataSource[indexPath.row];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equipment.equipmentId];
    NSArray *array = [self.selectEquipmentArray filteredArrayUsingPredicate:searchPredicate];
    if (array.count==0 && equipment) {
        [self.selectEquipmentArray addObject:equipment];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWEquipment *equipment = _dataSource[indexPath.row];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equipment.equipmentId];
    NSArray *array = [self.selectEquipmentArray filteredArrayUsingPredicate:searchPredicate];
    if (array.count==1 && equipment) {
        [self.selectEquipmentArray removeObject:array[0]];
    }
}

- (void)rightNowSelect{
    [self.dataSource removeAllObjects];
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentsWithBuildingId:self.buildingId ApartmentId:currentApartment.apartmentId floorId:currentFloor.floorId locationId:currentLocation.locationId eqipmentSubSystemType:currentSubSystem.subSystemTypeId equipmentTypeId:currentEquipmentType.equipmentTypeId page:page];
    [self.dataSource addObjectsFromArray:equipments];
    
    [self setupOwnEquipmentArray];
    
    [self.tableView reloadData];
}

- (void)setupOwnEquipmentArray{
    
    [self.ownEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equipment.equipmentId];
        NSArray *array = [[_dataSource filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            YWEquipment *equ = array[0];
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equ.equipmentId];
            NSArray *array = [self.selectEquipmentArray filteredArrayUsingPredicate:searchPredicate];
            if (array.count==0 && equ) {
                [self.selectEquipmentArray addObject:equ];
            }
        }
    }];
}

- (void)rightBarButtonItemEvent:(id)sender{
    //点完成
    if ([self.delegate respondsToSelector:@selector(selectInspectEquipments:)]) {
        [self.delegate selectInspectEquipments:self.selectEquipmentArray];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)selectEquipmentArray{
    if (!_selectEquipmentArray) {
        _selectEquipmentArray = [NSMutableArray array];
    }
    return _selectEquipmentArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
